package com.cn.xiongmeng.czlxz.taku;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.rewardvideo.api.ATRewardVideoAd;
import com.cn.xiongmeng.czlxz.MainApplication;
import com.cn.xiongmeng.czlxz.activity.IndexActivity;
import com.cn.xiongmeng.czlxz.activity.WorkActivity;
import com.cn.xiongmeng.czlxz.network.HttpClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class RewardVideoAd {
    private static final String TAG = "MainApplication";
    public static void showRewardVideoAd(Activity activity){
        MainApplication app = (MainApplication)(activity.getApplication());
        ATRewardVideoAd mRewardVideoAd = app.getRewardVideoAd();

        if (mRewardVideoAd == null){
            return;
        }

        if (mRewardVideoAd.isAdReady()) {
            mRewardVideoAd.show(activity);
        } else {
            new Handler(Looper.getMainLooper()).post(() -> {
                Toast.makeText(activity, "未加载到广告资源，请稍后...", Toast.LENGTH_LONG).show();
            });
            mRewardVideoAd.load(); // 异步的，所以执行load后立即判断isAdReady是没有意义的
        }
    }
    /* 用户点击提示，看完激励视频，执行如下方法
    * 1、当前时间存入缓存，key为“preRewardTime”
    * 2、展示提示圆圈
    * 3、任务数加一 */
    public static void onReward(Activity activity, String networkName, double ecpmLevel, double ecpm){
        // 1、当前时间存入缓存，key为“preRewardTime”
        SharedPreferences prefs = activity.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        long curDate = System.currentTimeMillis();
        editor.putLong("preRewardTime", curDate);
        editor.apply(); // apply异步，commit同步
        // 2、展示提示圆圈、haveTishi变更
        WorkActivity workActivity = (WorkActivity)activity;
        workActivity.wenzhangFragment.onClickTishi();
        workActivity.haveTishi = true;
        // 3、调用接口on_reward
        String fakeUser = prefs.getString("fakeUser", "");
        if (fakeUser.length() != 0){
            try {
                JSONObject jsonObject = new JSONObject(fakeUser);
                String fakeUid = jsonObject.getString("fake_uid");
                sendInformationToServer(activity, fakeUid, networkName, ecpmLevel, ecpm);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.d("RewardVideoAd", "onReward: 不处理");
        }
    }
    private static void sendInformationToServer(Activity activity, String fakeUid, String networkName, double ecpmLevel, double ecpm){
        String jsonString = null;
        try {
            JSONObject jsonObject = new JSONObject();

            String key1 = "fakeUid";
            String key2 = "networkName";
            String key3 = "ecpmLevel";
            String key4 = "ecpm";
            jsonObject.put(key1, fakeUid);
            jsonObject.put(key2, networkName);
            jsonObject.put(key3, ecpmLevel);
            jsonObject.put(key4, ecpm);
            jsonString = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.d(TAG, "jsonString: " + jsonString);

        HttpClient httpClient = new HttpClient(activity);
        String url = "https://little-moon.fun/on_reward/";

        httpClient.sendPostRequest(url, jsonString, new HttpClient.Callback() {
            @Override
            public void onFailure(Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(activity, "请稍后再试！", Toast.LENGTH_LONG).show();
                });
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    if (code.equals("200") || code.equals("201")){ // 更新成功，但是没完成任务
                        SharedPreferences prefs = activity.getSharedPreferences("AppPrefs", Context.MODE_PRIVATE);
                        String fakeUser = prefs.getString("fakeUser", "");
                        SharedPreferences.Editor editor = prefs.edit();
                        // 1、获取当前缓存的fakeUser
                        JSONObject jsonObject2 = new JSONObject(fakeUser);
                        // 2、获取当前缓存的cur_reward的值，并加一
                        int _curReward = jsonObject2.getInt("cur_reward");
                        String curReward = String.valueOf(_curReward + 1);
                        // 3、将这个新的cur_reward，存到fakeUser
                        jsonObject2.put("cur_reward", curReward);
                        // 4、更新缓存中的fakeUser
                        editor.putString("fakeUser", jsonObject2.toString());
                        editor.commit(); // apply异步，commit

                        int _curTargetReward = jsonObject2.getInt("cur_target_reward");
                        Log.d(TAG, "onResponse: 当前任务：" + curReward + " / " + _curTargetReward);

                        if (code.equals("201")) {
                            // 1. 更改样式
                            Log.d(TAG, "onResponse: 完成任务，任务样式变更");
                            // 2. 完成任务，禁止再看激励广告
                            SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault());
                            String formattedTime = dateFormat.format(new Date());

                            editor.putInt("completeTarget", 1);
                            editor.putString("completeTargetTime", formattedTime);
                            editor.apply(); // apply异步，commit
                        }
                    } else{
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Toast.makeText(activity, "请稍后再试！", Toast.LENGTH_LONG).show();
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
